package com.guo.core.framework.observable;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;

/**
 * 业务主题
 */
@Slf4j
public class BizSubject<D> {

    private final List<BizObserver<D>> consumers = new ArrayList<>();

    private Executor observerExecutor;

    public void setObserverExecutor(Executor observerExecutor) {
        this.observerExecutor = observerExecutor;
    }

    /**
     * 添加消费者
     */
    public BizSubject<D> add(BizObserver<D> bizObserver) {
        consumers.add(bizObserver);
        return this;
    }



    /**
     * 发布消息
     * @param data 发布消息
     */
    public void publish(D data) {
        if (observerExecutor == null) {
            consumers.forEach(consumer -> {
                try {
                    consumer.consume(data);
                } catch (InterruptedException e) {
                    log.error("通知异常", e);
                }
            });
            return ;
        }

        consumers.forEach(consumer -> observerExecutor.execute(() -> {
            try {
                consumer.consume(data);
            } catch (Exception e) {
                log.error("通知异常", e);
            }
        }));

    }

}
